package secondriver.spark.core;

import java.io.File;
import java.time.LocalTime;

import spark.Request;
import spark.Response;
import spark.Route;
import spark.Spark;

public class SparkEmitter {

	private static SparkEmitter sparkEmitter;

	public synchronized static SparkEmitter createSparkEmitter() {
		if (null == sparkEmitter) {
			sparkEmitter = new SparkEmitter();
		}
		return sparkEmitter;
	}

	public synchronized static SparkEmitter createSparkEmitter(
			SparkConfigure sparkConfigure, SparkFilter sparkFilter,
			SparkException sparkException, SparkException sparkHanlder) {
		if (null == sparkEmitter) {
			sparkEmitter = new SparkEmitter(sparkConfigure, sparkFilter,
					sparkException, sparkHanlder);
		}
		return sparkEmitter;
	}

	private SparkConfigure sparkConfigure = new SparkConfigure() {

		@Override
		public void init() {
			Spark.setIpAddress("localhost");
			Spark.setPort(9000);
			Spark.externalStaticFileLocation(System.getProperty("user.dir")
					+ File.separator + "/public");
			Spark.staticFileLocation(".");
		}
	};

	private SparkFilter sparkFilter = new SparkFilter() {

		@Override
		public void init() {

		}
	};

	private SparkException sparkException = new SparkException() {

		@Override
		public void init() {

		}
	};

	private SparkException sparkHanlder = new SparkException() {

		Route welcome = new Route() {

			@Override
			public Object handle(Request request, Response response) {
				return "<h2>" + "欢迎使用Spark" + "</h2>" + "<br/>" + "<h6>"
						+ LocalTime.now().toString() + "</h6>";
			}
		};

		@Override
		public void init() {
			Spark.get("/", welcome);
			Spark.get("/index", welcome);
		}
	};

	private SparkEmitter() {
		super();
	}

	private SparkEmitter(SparkConfigure sparkConfigure,
			SparkFilter sparkFilter, SparkException sparkException,
			SparkException sparkHanlder) {
		super();
		if (null != sparkConfigure) {
			this.sparkConfigure = sparkConfigure;
		}
		if (null != sparkFilter) {
			this.sparkFilter = sparkFilter;
		}
		if (null != sparkHanlder) {
			this.sparkHanlder = sparkHanlder;
		}
		if (null != sparkException) {
			this.sparkException = sparkException;
		}
	}

	public synchronized void launch() {
		// Notice: this.sparkConfigure.init() Must call firstly.
		this.sparkConfigure.init();
		this.sparkFilter.init();
		this.sparkHanlder.init();
		this.sparkException.init();
	}

}